import React, { useState, useEffect } from 'react';
import { Form, TimePicker, Checkbox, Card, Row, Col, Tabs, Button, Space, message } from 'antd';
import { CopyOutlined } from '@ant-design/icons';
import moment from 'moment';

/**
 * 营业时间编辑组件
 * 用于设置门店的营业时间，支持工作日和周末分别设置
 * @param {Object} props
 * @param {String} props.value - 当前营业时间JSON字符串
 * @param {Function} props.onChange - 值变化回调
 */
const BusinessHoursEditor = ({ value = '', onChange }) => {
  // 默认营业时间数据
  const defaultTimeData = {
    workday: {
      isOpen: true,
      openTime: '00:00',
      closeTime: '23:59'
    },
    weekend: {
      isOpen: true,
      openTime: '00:00',
      closeTime: '23:59'
    },
    // 保留每天单独设置的选项，以便后续扩展
    daily: [
      { day: 1, dayName: '周一', isOpen: true, openTime: '00:00', closeTime: '23:59' },
      { day: 2, dayName: '周二', isOpen: true, openTime: '00:00', closeTime: '23:59' },
      { day: 3, dayName: '周三', isOpen: true, openTime: '00:00', closeTime: '23:59' },
      { day: 4, dayName: '周四', isOpen: true, openTime: '00:00', closeTime: '23:59' },
      { day: 5, dayName: '周五', isOpen: true, openTime: '00:00', closeTime: '23:59' },
      { day: 6, dayName: '周六', isOpen: true, openTime: '00:00', closeTime: '23:59' },
      { day: 7, dayName: '周日', isOpen: true, openTime: '00:00', closeTime: '23:59' }
    ]
  };

  // 状态初始化
  const [timeData, setTimeData] = useState(defaultTimeData);
  const [activeTab, setActiveTab] = useState('simple'); // simple 或 advanced

  // 初始化时间数据
  useEffect(() => {
    if (value) {
      try {
        // 尝试解析JSON字符串
        const parsedValue = JSON.parse(value);
        setTimeData(parsedValue);
      } catch (error) {
        // 如果不是JSON格式，使用默认值
        console.error('解析营业时间数据失败:', error);
        // 尝试将字符串格式化为简单模式
        if (typeof value === 'string' && value.trim()) {
          const simpleFormat = {
            ...defaultTimeData,
            workday: {
              ...defaultTimeData.workday,
              openTime: '00:00',
              closeTime: '23:59'
            },
            weekend: {
              ...defaultTimeData.weekend,
              openTime: '00:00',
              closeTime: '23:59'
            }
          };
          setTimeData(simpleFormat);
        } else {
          setTimeData(defaultTimeData);
        }
      }
    } else {
      setTimeData(defaultTimeData);
    }
  }, [JSON.stringify(value)]);

  // 处理工作日时间变更
  const handleWorkdayChange = (field, value) => {
    const newTimeData = { ...timeData };
    
    if (field === 'isOpen') {
      newTimeData.workday.isOpen = value;
    } else if (field === 'openTime') {
      newTimeData.workday.openTime = value.format('HH:mm');
    } else if (field === 'closeTime') {
      newTimeData.workday.closeTime = value.format('HH:mm');
    }
    
    // 同步更新每日数据中的工作日
    newTimeData.daily = newTimeData.daily.map(item => {
      if (item.day >= 1 && item.day <= 5) { // 周一至周五
        return {
          ...item,
          isOpen: newTimeData.workday.isOpen,
          openTime: newTimeData.workday.openTime,
          closeTime: newTimeData.workday.closeTime
        };
      }
      return item;
    });
    
    setTimeData(newTimeData);
    onChange(JSON.stringify(newTimeData));
  };

  // 处理周末时间变更
  const handleWeekendChange = (field, value) => {
    const newTimeData = { ...timeData };
    
    if (field === 'isOpen') {
      newTimeData.weekend.isOpen = value;
    } else if (field === 'openTime') {
      newTimeData.weekend.openTime = value.format('HH:mm');
    } else if (field === 'closeTime') {
      newTimeData.weekend.closeTime = value.format('HH:mm');
    }
    
    // 同步更新每日数据中的周末
    newTimeData.daily = newTimeData.daily.map(item => {
      if (item.day >= 6 && item.day <= 7) { // 周六和周日
        return {
          ...item,
          isOpen: newTimeData.weekend.isOpen,
          openTime: newTimeData.weekend.openTime,
          closeTime: newTimeData.weekend.closeTime
        };
      }
      return item;
    });
    
    setTimeData(newTimeData);
    onChange(JSON.stringify(newTimeData));
  };

  // 处理每日时间变更
  const handleDailyChange = (day, field, value) => {
    const newTimeData = { ...timeData };
    const index = newTimeData.daily.findIndex(item => item.day === day);
    
    if (index !== -1) {
      if (field === 'isOpen') {
        newTimeData.daily[index].isOpen = value;
      } else if (field === 'openTime') {
        newTimeData.daily[index].openTime = value.format('HH:mm');
      } else if (field === 'closeTime') {
        newTimeData.daily[index].closeTime = value.format('HH:mm');
      }
    }
    
    // 更新工作日和周末的汇总数据
    updateSummaryFromDaily(newTimeData);
    
    setTimeData(newTimeData);
    onChange(JSON.stringify(newTimeData));
  };

  // 从每日数据更新汇总数据
  const updateSummaryFromDaily = (data) => {
    // 检查工作日是否统一
    const workdays = data.daily.filter(item => item.day >= 1 && item.day <= 5);
    const workdayOpenTimes = [...new Set(workdays.map(item => item.openTime))];
    const workdayCloseTimes = [...new Set(workdays.map(item => item.closeTime))];
    const workdayIsOpen = [...new Set(workdays.map(item => item.isOpen))];
    
    if (workdayOpenTimes.length === 1 && workdayCloseTimes.length === 1 && workdayIsOpen.length === 1) {
      data.workday = {
        isOpen: workdayIsOpen[0],
        openTime: workdayOpenTimes[0],
        closeTime: workdayCloseTimes[0]
      };
    }
    
    // 检查周末是否统一
    const weekends = data.daily.filter(item => item.day >= 6 && item.day <= 7);
    const weekendOpenTimes = [...new Set(weekends.map(item => item.openTime))];
    const weekendCloseTimes = [...new Set(weekends.map(item => item.closeTime))];
    const weekendIsOpen = [...new Set(weekends.map(item => item.isOpen))];
    
    if (weekendOpenTimes.length === 1 && weekendCloseTimes.length === 1 && weekendIsOpen.length === 1) {
      data.weekend = {
        isOpen: weekendIsOpen[0],
        openTime: weekendOpenTimes[0],
        closeTime: weekendCloseTimes[0]
      };
    }
  };

  // 复制工作日设置到所有工作日
  const copyToAllWorkdays = () => {
    const newTimeData = { ...timeData };
    newTimeData.daily = newTimeData.daily.map(item => {
      if (item.day >= 1 && item.day <= 5) { // 周一至周五
        return {
          ...item,
          isOpen: newTimeData.workday.isOpen,
          openTime: newTimeData.workday.openTime,
          closeTime: newTimeData.workday.closeTime
        };
      }
      return item;
    });
    
    setTimeData(newTimeData);
    onChange(JSON.stringify(newTimeData));
    message.success('已复制到所有工作日');
  };

  // 复制周末设置到所有周末
  const copyToAllWeekends = () => {
    const newTimeData = { ...timeData };
    newTimeData.daily = newTimeData.daily.map(item => {
      if (item.day >= 6 && item.day <= 7) { // 周六和周日
        return {
          ...item,
          isOpen: newTimeData.weekend.isOpen,
          openTime: newTimeData.weekend.openTime,
          closeTime: newTimeData.weekend.closeTime
        };
      }
      return item;
    });
    
    setTimeData(newTimeData);
    onChange(JSON.stringify(newTimeData));
    message.success('已复制到所有周末');
  };

  // 复制某天设置到全周
  const copyToAll = (sourceDay) => {
    const source = timeData.daily.find(item => item.day === sourceDay);
    if (source) {
      const newTimeData = { ...timeData };
      newTimeData.daily = newTimeData.daily.map(item => {
        if (item.day !== sourceDay) {
          return {
            ...item,
            isOpen: source.isOpen,
            openTime: source.openTime,
            closeTime: source.closeTime
          };
        }
        return item;
      });
      
      // 更新工作日和周末的汇总数据
      updateSummaryFromDaily(newTimeData);
      
      setTimeData(newTimeData);
      onChange(JSON.stringify(newTimeData));
      message.success('已复制到全周');
    }
  };

  // 格式化为用户友好的显示
  const formatForDisplay = () => {
    if (activeTab === 'simple') {
      const workday = timeData.workday;
      const weekend = timeData.weekend;
      
      const workdayText = workday.isOpen 
        ? `工作日: ${workday.openTime}-${workday.closeTime}` 
        : '工作日: 休息';
      
      const weekendText = weekend.isOpen 
        ? `周末: ${weekend.openTime}-${weekend.closeTime}` 
        : '周末: 休息';
      
      return `${workdayText}, ${weekendText}`;
    } else {
      // 高级模式下返回每天的时间
      return timeData.daily
        .map(item => {
          return item.isOpen 
            ? `${item.dayName}: ${item.openTime}-${item.closeTime}` 
            : `${item.dayName}: 休息`;
        })
        .join('; ');
    }
  };

  return (
    <div className="business-hours-editor">
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={[
          {
            key: 'simple',
            label: '简单模式',
            children: (
              <div>
                <Card title="工作日营业时间" size="small" extra={(
                  <Button 
                    type="link" 
                    icon={<CopyOutlined />} 
                    onClick={copyToAllWorkdays}
                  >
                    应用到所有工作日
                  </Button>
                )}>
                  <Row gutter={16} align="middle">
                    <Col span={6}>
                      <Checkbox 
                        checked={timeData?.workday?.isOpen} 
                        onChange={(e) => handleWorkdayChange('isOpen', e.target.checked)}
                      >
                        营业
                      </Checkbox>
                    </Col>
                    <Col span={8}>
                      <TimePicker 
                        format="HH:mm" 
                        value={moment(timeData?.workday?.openTime || '00:00', 'HH:mm')} 
                        onChange={(time) => handleWorkdayChange('openTime', time)}
                        disabled={!timeData?.workday?.isOpen}
                      />
                    </Col>
                    <Col span={2} style={{ textAlign: 'center' }}>至</Col>
                    <Col span={8}>
                      <TimePicker 
                        format="HH:mm" 
                        value={moment(timeData?.workday?.closeTime || '23:59', 'HH:mm')} 
                        onChange={(time) => handleWorkdayChange('closeTime', time)}
                        disabled={!timeData?.workday?.isOpen}
                      />
                    </Col>
                  </Row>
                </Card>
                
                <Card title="周末营业时间" size="small" style={{ marginTop: 16 }} extra={(
                  <Button 
                    type="link" 
                    icon={<CopyOutlined />} 
                    onClick={copyToAllWeekends}
                  >
                    应用到所有周末
                  </Button>
                )}>
                  <Row gutter={16} align="middle">
                    <Col span={6}>
                      <Checkbox 
                        checked={timeData.weekend.isOpen} 
                        onChange={(e) => handleWeekendChange('isOpen', e.target.checked)}
                      >
                        营业
                      </Checkbox>
                    </Col>
                    <Col span={8}>
                      <TimePicker 
                        format="HH:mm" 
                        value={moment(timeData.weekend.openTime, 'HH:mm')} 
                        onChange={(time) => handleWeekendChange('openTime', time)}
                        disabled={!timeData.weekend.isOpen}
                      />
                    </Col>
                    <Col span={2} style={{ textAlign: 'center' }}>至</Col>
                    <Col span={8}>
                      <TimePicker 
                        format="HH:mm" 
                        value={moment(timeData.weekend.closeTime, 'HH:mm')} 
                        onChange={(time) => handleWeekendChange('closeTime', time)}
                        disabled={!timeData.weekend.isOpen}
                      />
                    </Col>
                  </Row>
                </Card>
              </div>
            ),
          },
          {
            key: 'advanced',
            label: '高级模式',
            children: (
              <div>
                {timeData.daily.map((item) => (
                  <Card 
                    key={item.day} 
                    title={item.dayName} 
                    size="small" 
                    style={{ marginBottom: 8 }}
                    extra={(
                      <Button 
                        type="link" 
                        icon={<CopyOutlined />} 
                        onClick={() => copyToAll(item.day)}
                        disabled={!item.isOpen}
                      >
                        复制到全周
                      </Button>
                    )}
                  >
                    <Row gutter={16} align="middle">
                      <Col span={6}>
                        <Checkbox 
                          checked={item.isOpen} 
                          onChange={(e) => handleDailyChange(item.day, 'isOpen', e.target.checked)}
                        >
                          营业
                        </Checkbox>
                      </Col>
                      <Col span={8}>
                        <TimePicker 
                          format="HH:mm" 
                          value={moment(item.openTime, 'HH:mm')} 
                          onChange={(time) => handleDailyChange(item.day, 'openTime', time)}
                          disabled={!item.isOpen}
                          minuteStep={15}
                        />
                      </Col>
                      <Col span={2} style={{ textAlign: 'center' }}>至</Col>
                      <Col span={8}>
                        <TimePicker 
                          format="HH:mm" 
                          value={moment(item.closeTime, 'HH:mm')} 
                          onChange={(time) => handleDailyChange(item.day, 'closeTime', time)}
                          disabled={!item.isOpen}
                          minuteStep={15}
                        />
                      </Col>
                    </Row>
                  </Card>
                ))}
              </div>
            ),
          },
        ]}
      />
      
      <div className="business-hours-preview" style={{ marginTop: 16, color: '#666' }}>
        <div>预览: {formatForDisplay()}</div>
      </div>
    </div>
  );
};

export default BusinessHoursEditor;